<template>
	<view class="pages">
		<!-- <view class="statusbar"></view>
		<view class="title"> {{ $t('search') }} </view> -->
		<block v-if="show == 1">
			<view class="index-search">
				<view class="index-search-left">
					<image src="../../static/img/search.png" mode="aspectFill"></image>
					<image src="../../static/img/chicken.gif" class="pic" :class="isActive? 'active' : ''"></image>
					<input type="text" placeholder="搜索" v-model="searchWord" @confirm="handelSearchWord(searchWord)"
						@focus="focus" @blur="blur" />
				</view>
			</view>
			<view class="search-history">
				<view class="search-history-head">
					<view>搜索历史</view>
					<image src="@/static/img/delete.png" mode="aspectFit" @click="cancelHistory"></image>
				</view>
				<view class="search-history-list">
					<view class="item" v-for="(word,index) in searchHistory" :key="index"
						@click="navigatorToSearchByHw(word)">
						{{word}}
					</view>
				</view>
			</view>
		</block>
		<block v-else-if="show == 2">
			<view class="index-search">
				<view class="index-search-left">
					<image src="../../static/img/search.png" mode="aspectFill"></image>
					<input type="text" placeholder="搜索歌曲" v-model="searchWord"
						@confirm="handelSearchWord(searchWord)" />
				</view>
				<image id="cancel" src="../../static/img/cancel.png" mode="aspectFill" @click="navigatorSearch"></image>
			</view>

			<view class="search-result">
				<scroll-view show-scrollbar="true" style="height: 990rpx" scroll-y="true"
					:refresher-enabled="isOpenRefresh" :refresher-triggered="triggered" :refresher-threshold="100"
					refresher-background="gray" @scrolltolower="scrolltolowerFun" @refresherpulling="onPulling"
					@refresherrefresh="onRefresh" @refresherrestore="onRestore" @refresherabort="onAbort">
					<view class="search-result-word">
						<shortlist :list="dataList" />
					</view>
					<uni-load-more v-if="!isOpenRefresh" iconType="circle" :status="status" />
					<view style="height: calc(100rpx + env(safe-area-inset-bottom))">
					</view>
				</scroll-view>
			</view>
		</block>
	</view>
</template>

<script>
	import shortlist from '@/components/vertical.vue'
	import request from '@/common/request'

	export default {
		components: {
			shortlist
		},
		data() {
			return {
				dataList: [],
				videoCount: 0,
				videoPageNo: 0,
				videoPageSize: 500,
				searchWord: '',
				searchHistory: [],
				show: 1,
				loading: false, // 加载状态锁（防止重复请求）
				hotSearchs: [],
				isActive: false,
				triggered: false,
				isOpenRefresh: true, // 是否开启下拉
				status: 'noMore',
				hasMore: true,
			};
		},
		onLoad() {
			this.requestReset()
			this._freshing = false;
			uni.getStorage({
				key: 'searchHistory',
				success: res => {
					this.searchHistory = res.data;
				}
			})
		},
		methods: {
			focus() {
				this.isActive = true;
			},
			blur() {
				this.isActive = false;
			},
			handelSearchWord(word) {
				this.searchHistory.unshift(word);
				this.searchHistory = [...new Set(this.searchHistory)];
				if (this.searchHistory.length > 10) {
					this.searchHistory.length = 10;
				}
				uni.setStorage({
					key: 'searchHistory',
					data: this.searchHistory
				})
				this.requestReset()
				this.getSearchList(word);
			},
			/**
			 * 清除历史搜索
			 */
			cancelHistory() {
				uni.removeStorage({
					key: 'searchHistory',
					success: (res) => {
						this.searchHistory = [];
					}
				})
			},
			/**
			 * 搜索
			 * @param {Object} word
			 */
			async getSearchList(word) {
				if (!word) {
					return
				}
				this.show = 2;
				//搜索结果成功以后再跳 this.show = 2;
				if (this.loading || !this.hasMore) {
					return;
				}
				uni.showLoading({
					title: '搜索中'
				});
				let userTmp1 = uni.getStorageSync('user')
				if (!userTmp1) {
					return
				}
				this.loading = true;
				let userTmp = JSON.parse(userTmp1)
				this.videoPageNo = (this.videoPageNo <= 0 ? 1 : this.videoPageNo)
				let getJSON = {
					Fields: "BasicSyncInfo,CanDelete,PrimaryImageAspectRatio,ProductionYear,Status,EndDate,Width,Height,Size,Tags,DateCreated",
					StartIndex: (this.videoPageNo - 1) * this.videoPageSize,
					SortBy: "SortName",
					SortOrder: "Ascending",
					EnableImageTypes: "Primary,Backdrop,Thumb",
					ImageTypeLimit: 1,
					Recursive: true,
					SearchTerm: word,
					GroupProgramsBySeries: true,
					Limit: this.videoPageSize
				}
				let urlAppend = this.jsonToGetParams(getJSON)
				const data = await request.get(`/emby/Users/${userTmp.userId}/Items${urlAppend}`)
				let videoList = data.Items
				this.videoCount = data.TotalRecordCount
				// console.log("请求返回数据" + JSON.stringify(videoList))
				if (!videoList || videoList.length == 0) {
					this.hasMore = false;
					this.loading = false;
					uni.hideLoading();
					return
				}
				let serverUrl = `${userTmp.serverip}:${userTmp.serverport}`
				if (!serverUrl.startsWith('http')) {
					serverUrl = `http://${serverUrl}`
				}
				for (const item of videoList) {
					let imageStr = `${serverUrl}/emby/Items/${item.Id}/Images/Primary`
					item.cover = imageStr
				}
				this.dataList = [...this.dataList, ...videoList];
				if (this.dataList.length >= this.videoCount) {
					this.hasMore = false;
					uni.hideLoading();
				}
				this.loading = false; // 释放锁
			},
			/**
			 * 关键词搜索
			 * @param {Object} word
			 */
			navigatorToSearchByHw(word) {
				this.requestReset();
				this.searchWord = word;
				this.getSearchList(word);
			},
			requestReset() {
				this.hasMore = true;
				this.videoPageNo = 1;
				this.dataList = []
			},
			navigatorSearch() {
				this.requestReset();
				this.show = 1;
				this.searchWord = '';
			},
			/**
			 * 将JSON对象转换为GET请求的查询参数
			 * @param {Object} json - 输入的JSON对象，如 { aa: '11', bb: '22' }
			 * @returns {String} 拼接后的查询参数字符串，如 ?aa=11&bb=22
			 */
			jsonToGetParams(json) {
				// 处理空对象
				if (!json || Object.keys(json).length === 0) {
					return '';
				}

				// 存储键值对数组
				const params = [];

				// 遍历JSON的键值对
				for (const key in json) {
					// 过滤原型链上的属性
					if (json.hasOwnProperty(key)) {
						const value = json[key];
						// 对键和值进行URL编码（处理特殊字符和中文）
						const encodedKey = encodeURIComponent(key);
						const encodedValue = encodeURIComponent(String(value)); // 转为字符串后编码
						params.push(`${encodedKey}=${encodedValue}`);
					}
				}

				// 拼接成 ?key1=value1&key2=value2 格式
				return `?${params.join('&')}`;
			},
			// 自定义下拉刷新控件被下拉
			onPulling(e) {
				// console.log("onpulling", e);
				if (e.detail.deltaY < 0) return // 防止上滑页面也触发下拉
				this.triggered = true;
			},
			// 自定义下拉刷新被触发
			onRefresh() {
				if (this._freshing) return;
				this._freshing = true;
				setTimeout(() => {
					this.triggered = false;
					this._freshing = false;
					if (this.searchWord) {
						this.requestReset();
						this.getSearchList(this.searchWord)
					}
				}, 500);
			},
			// 自定义下拉刷新被复位
			onRestore() {
				this.triggered = 'restore'; // 需要重置
			},
			// 自定义下拉刷新被中止
			onAbort() {
				console.error("onAbort");
			},
			//上拉加载，页面滑动到底部加载分页数据
			scrolltolowerFun() {
				if (!this.hasMore) {
					this.status = 'noMore';
					return
				}
				this.status = 'loading'
				if (this.searchWord) {
					this.videoPageNo++
					this.getSearchList(this.searchWord)
				}
			},
		}
	}
</script>

<style lang="scss">
	.index-search {
		height: 70rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		margin: 40rpx 30rpx 30rpx 30rpx;
		background-color: #f7f7f7;
		border-radius: 50rpx;

		image {
			width: 26rpx;
			height: 26rpx;
			margin-left: 20rpx;
			margin-right: 20rpx;
		}

		#cancel {
			margin-left: 200rpx;
		}

		.index-search-left {
			display: flex;
			justify-content: space-around;
			align-items: center;
			position: relative;

			input {
				position: relative;
				z-index: 2;
				background: #ffffff;
				color: #000000;
			}

			.pic {
				height: 24rpx;
				width: 24rpx;
				position: absolute;
				z-index: 1;
				top: 0;
				left: 200rpx -12rpx;
				transition: top 0.3s;
			}

			.pic.active {
				top: -24rpx;
			}
		}
	}

	.search-history {
		.search-history-head {
			display: flex;
			flex-direction: row;
			margin: 0 30rpx;
			font-size: 28rpx;
			justify-content: space-between;

			image {
				width: 35rpx;
				height: 35rpx;
				margin-left: 35rpx;
				margin-right: 35rpx;
			}
		}

		.search-history-list {
			display: flex;
			margin-top: 20rpx;
			flex-wrap: wrap;

			.item {
				// background: #f7f7f7;
				border-radius: 30rpx;
				padding: 20rpx 10rpx;
				margin: 5rpx 30rpx;
			}
		}
	}

	.search-hot {
		.search-hot-head {
			margin: 0 30rpx;
			margin-top: 10rpx;
			font-size: 30rpx;
		}

		.search-hot-item {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			background: #f7f7f7;
			border-radius: 30rpx;
			margin: 30rpx 30rpx;
			padding: 10rpx;

			.search-hot-left {
				padding-top: 20rpx;
			}

			.search-hot-main {
				font-size: 35rpx;
				display: flex;
				align-items: center;
				padding-left: 20rpx;

				image {
					width: 20rpx;
					height: 20rpx;
					margin-left: 5rpx;
				}

				.second {
					margin-left: 20rpx;
				}

				.search-hot-main-bot {
					font-size: 25rpx;
				}
			}

			.search-hot-right {
				padding-top: 20rpx;
				font-size: 29rpx;
			}
		}
	}

	.search-result-word {
		padding: 20rpx 40rpx;

		// border: 2rpx solid #efefef;
		.search-result-word {
			margin-top: 20rpx;
		}
	}
</style>